<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
     
      <el-form-item label="员工姓名" prop="staffName">
        <el-input
          v-model="queryParams.staffName"
          placeholder="请输入员工"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="部门" prop="deptId">
        

        <el-select
              v-model="queryParams.deptId"
              placeholder="请选择部门" @change="selectChange" style="width:100%"
            >
              <el-option v-for="item in deptlist" :key="item.deptId" :value="item.deptId" :label="item.deptName"/>
            </el-select>
     
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <!-- <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['hrmanagement:insurance:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['hrmanagement:insurance:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['hrmanagement:insurance:remove']"
        >删除</el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['hrmanagement:insurance:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="insuranceList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <!-- <el-table-column label="城市id" align="center" prop="cityId" /> -->
      <el-table-column label="员工号" align="center" prop="staffId" />
      <el-table-column prop="name" label="姓名" min-width="125" align="center"/>
        <el-table-column prop="deptName" label="部门" min-width="125" align="center"/>
        <el-table-column prop="phone" label="电话" min-width="125" align="center"/>
        <el-table-column label="社保"  align="center">
          <el-table-column prop="socialBase" label="缴纳基数" min-width="125" align="center"/>
          <el-table-column label="个人">
            <el-table-column prop="perSocialPay" label="缴纳费用" min-width="125" align="center"/>
          </el-table-column>
          <el-table-column label="企业">
            <el-table-column prop="comInjuryRate" label="工伤保险缴纳比例" min-width="125" align="center"/>
            <el-table-column prop="comSocialPay" label="缴纳费用" min-width="125" align="center"/>
          </el-table-column>
          <el-table-column prop="socialRemark" label="备注" min-width="200" align="center"/>
        </el-table-column>
        <el-table-column label="公积金"  align="center">
          <el-table-column prop="houseBase" label="缴纳基数" min-width="125" align="center"/>
          <el-table-column label="个人">
            <el-table-column prop="perHouseRate" label="缴纳比例" min-width="125" align="center"/>
            <el-table-column prop="perHousePay" label="缴纳费用" min-width="125" align="center"/>
          </el-table-column>
          <el-table-column label="企业">
            <el-table-column prop="comHouseRate" label="缴纳比例" min-width="125" align="center"/>
            <el-table-column prop="comHousePay" label="缴纳费用" min-width="125" align="center"/>
          </el-table-column>
          <el-table-column prop="houseRemark" label="备注" min-width="200" align="center"/>
        </el-table-column>
      <el-table-column label="操作" align="" class-name="small-padding fixed-width" fixed="right" min-width="150" align="center">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['hrmanagement:insurance:edit']"
          >详情设置</el-button>
          <!-- <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['hrmanagement:insurance:remove']"
          >删除</el-button> -->
        </template>
      </el-table-column>
    </el-table>
    
    <el-drawer
  :title="title"
  :visible.sync="open"
  direction="rtl"
  size="50%"
  >
  <div style="padding-right: 30px;">
    <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="参保城市" prop="cityId">
            <el-select
              v-model="form.cityId"
              placeholder="请选择参保城市" @change="selectChange2" style="width:38%"
            >
              <el-option v-for="item in CityList" :key="item.id" :value="item.id" :label="item.name"/>
            </el-select>
          </el-form-item>

          <el-form-item label="社保基数" prop="socialBase">
            <el-input-number v-model="form.socialBase" style="width:38%" :precision="3"/>
            （基数范围：{{ insuranceTable.tableData[0].socLowerLimit }}￥ ~ {{
              insuranceTable.tableData[0].socUpperLimit
            }}￥）
          </el-form-item>

          <el-form-item label="工伤比例" prop="comInjuryRate">
            <el-input-number v-model="form.comInjuryRate" style="width:38%" :step="0.001"
                             :precision="3"/>
            （比例范围：0.002 ~ 0.019，推荐0.019）
          </el-form-item>

          <el-form-item label="社保缴纳">
            <el-form-item label="个人" prop="perSocialPay" label-width="50px" style="display:inline-block">
              <el-input-number
                v-model="form.perSocialPay"
                :disabled="true"
                :controls="false"
                :precision="3"
              ></el-input-number>
            </el-form-item>
            <el-form-item label="公司" prop="comSocialPay" label-width="50px" style="display:inline-block">
              <el-input-number
                v-model="form.comSocialPay"
                :disabled="true"
                :controls="false"
                :precision="3"
              ></el-input-number>
            </el-form-item>
            <el-table :data="insuranceTable.tableData" border stripe :header-cell-style="{background: '#eef1f6',color: '#606266',
        textAlign:'center',fontWeight:'bold',borderWidth:'3px'}">
              <el-table-column label="养老保险缴费比例" align="center">
                <el-table-column label="个人" prop="perPensionRate" align="center"/>
                <el-table-column label="企业" prop="comPensionRate" align="center"/>
              </el-table-column>
              <el-table-column label="医疗保险缴费比例" align="center">
                <el-table-column label="个人" prop="perMedicalRate" align="center"/>
                <el-table-column label="企业" prop="comMedicalRate" align="center"/>
              </el-table-column>
              <el-table-column label="失业保险缴费比例" align="center">
                <el-table-column label="个人" prop="perUnemploymentRate" align="center"/>
                <el-table-column label="企业" prop="comUnemploymentRate" align="center"/>
              </el-table-column>
              <el-table-column label="生育保险企业缴费比例" prop="comMaternityRate" align="center"/>
            </el-table>

          </el-form-item>
          <el-form-item label="社保备注" prop="socialRemark">
            <el-input
              v-model.trim="form.socialRemark"
              type="textarea"
              :rows="2"
              placeholder="1-300字符"
              maxlength="300"
              style="width:38%"
              show-word-limit
            ></el-input>
          </el-form-item>

          <el-form-item label="公积金基数" prop="houseBase">
            <el-input-number v-model="form.houseBase" style="width:38%" :precision="3"/>
            （基数范围：{{ insuranceTable.tableData[0].houLowerLimit }}￥ ~ {{
              insuranceTable.tableData[0].houUpperLimit
            }}￥）
          </el-form-item>
          <el-form-item label="企业比例" prop="comHouseRate">
            <el-input-number v-model="form.comHouseRate" style="width:38%" :precision="3" :step="0.001"/>
            （比例范围：0.05 ~ 0.12，推荐0.12）
          </el-form-item>
          <el-form-item label="个人比例" prop="perHouseRate">
            <el-input-number v-model="form.perHouseRate" style="width:38%" :precision="3" :step="0.001"/>
            （比例范围：0.05 ~ 0.12，推荐0.12）
          </el-form-item>
          <el-form-item label="公积金缴纳">
            <el-form-item label="个人" label-width="50px" style="display:inline-block" prop="perHousePay">
              <el-input-number v-model="form.perHousePay" :disabled="true"
                               :controls="false" :precision="3"/>
            </el-form-item>
            <el-form-item label="公司" label-width="50px" style="display:inline-block" prop="comHousePay">
              <el-input-number v-model="form.comHousePay" :disabled="true"
                               :controls="false" :precision="3"/>
            </el-form-item>
          </el-form-item>
          <el-form-item label="公积金备注" prop="houseRemark">
            <el-input v-model.trim="form.houseRemark" type="textarea" :rows="2" placeholder="1-300字符"
                      style="width:38%" maxlength="300"
                      show-word-limit/>
          </el-form-item>
      </el-form>
      <div slot="footer" style="text-align: right;margin-right: 20px;">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
  </div>
</el-drawer>
    <!-- 添加或修改员工五险一金对话框 -->

      
  
  </div>
</template>

<script>
import { listInsurance, getInsurance, delInsurance, addInsurance, updateInsurance } from "@/api/hrmanagement/insurance";

import { AllDept } from "@/api/system/dept";
import { allgetCity,getCity } from "@/api/hrmanagement/city";



export default {
  name: "Insurance",
  data() {
    const checkSocialBase = (rule, value, callback) => {
      if (value < this.insuranceTable.tableData[0].socLowerLimit || value > this.insuranceTable.tableData[0].socUpperLimit) {
        callback(new Error('社保基数应该在' + this.insuranceTable.tableData[0].socLowerLimit + ' ~ ' + this.insuranceTable.tableData[0].socUpperLimit + '之间'))
      } else {
        callback()
      }
    }
    const checkComInjuryRate = (rule, value, callback) => {
      if (value < 0.002 || value > 0.019) {
        callback(new Error('工伤保险企业缴费比例应在0.002 ~ 0.019之间'))
      } else {
        callback()
      }
    }
    const checkHouseBase = (rule, value, callback) => {
      if (value < this.insuranceTable.tableData[0].houLowerLimit || value > this.insuranceTable.tableData[0].houUpperLimit) {
        callback(new Error('公积金基数应该在' + this.insuranceTable.tableData[0].houLowerLimit + ' ~ ' + this.insuranceTable.tableData[0].houUpperLimit + '之间'))
      } else {
        callback()
      }
    }
    const checkHouseRate = (rule, value, callback) => {
      if (value < 0.05 || value > 0.12) {
        callback(new Error('公积金缴费比例应在0.05 ~ 0.12之间'))
      } else {
        callback()
      }
    }
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 员工五险一金表格数据
      insuranceList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      CityList:[],
      open: false,
      // 查询参数

      deptlist:[],
      queryParams: {
       
        pageNum: 1,
        pageSize: 10,
        cityId: null,
        staffId: null,
        houseBase: null,
        perHouseRate: null,
        perHousePay: null,
        comHouseRate: null,
        comHousePay: null,
        socialBase: null,
        comSocialPay: null,
        perSocialPay: null,
        comInjuryRate: null,
        socialRemark: null,
        houseRemark: null,
        status: null,
        isDeleted: null
      },
      // 表单参数
      form: {},
      // 表单校验
      insuranceTable: {
        tableData: [{
          socLowerLimit: 0,
          socUpperLimit: 0,
          houLowerLimit: 0,
          houUpperLimit: 0
        }]
      },
      rules: {
          cityId: [
            { required: true, message: '请选择参保地', trigger: 'change' }
          ],
          socialBase: [
            { required: true, message: '请输入社保基数', trigger: 'blur' },
            { validator: checkSocialBase, trigger: 'blur' }
          ],
          comInjuryRate: [
            { required: true, message: '请输入工伤保险企业缴费比例', trigger: 'blur' },
            { validator: checkComInjuryRate, trigger: 'blur' }
          ],
          houseBase: [
            { required: true, message: '请输入公积金基数', trigger: 'blur' },
            { validator: checkHouseBase, trigger: 'blur' }
          ],
          comHouseRate: [
            { required: true, message: '请输入公积金企业缴费比例', trigger: 'blur' },
            { validator: checkHouseRate, trigger: 'blur' }
          ],
          perHouseRate: [
            { required: true, message: '请输入公积金个人缴费比例', trigger: 'blur' },
            { validator: checkHouseRate, trigger: 'blur' }
          ]
        }
    };
  },
  watch: {
    'form.socialBase': function () {
      this.calculatePerSocialPay()
      this.calculateComSocialPay()
    },
    'form.comInjuryRate': function () {
      this.calculateComSocialPay()
    },
    'form.houseBase': function () {
      this.calculatePerHousePay()
      this.calculateComHousePay()
    },
    'form.comHouseRate': function () {
      this.calculateComHousePay()
    },
    'form.perHouseRate': function () {
      this.calculatePerHousePay()
    }
  },
  created() {
    this.getList();
    this.allgetCity();
    
    
    AllDept().then(response => {
          if (response.code === 200) {
            this.deptlist= response.data
          } else {
            this.$message.error(response.message)
          }
        })

  },
  methods: {
    calculatePerSocialPay () {
      this.form.perSocialPay = (this.insuranceTable.tableData[0].perPensionRate +
        this.insuranceTable.tableData[0].perMedicalRate +
        this.insuranceTable.tableData[0].perUnemploymentRate) * this.form.socialBase
    },
    calculateComSocialPay () {
      this.form.comSocialPay = (this.insuranceTable.tableData[0].comPensionRate +
        this.insuranceTable.tableData[0].comMedicalRate +
        this.insuranceTable.tableData[0].comUnemploymentRate + this.insuranceTable.tableData[0].comMaternityRate +
        this.form.comInjuryRate) * this.form.socialBase
    },
    calculatePerHousePay () {
      this.form.perHousePay = this.form.perHouseRate * this.form.houseBase
    },
    calculateComHousePay () {
      this.form.comHousePay = this.form.comHouseRate * this.form.houseBase
    },
    selectChange(){
this.getList()
    },
    selectChange2(id){
      console.log('城市id', id)
      this.CityList.forEach(item => {
        if (item.id === id) {
          this.insuranceTable.tableData = [item]
        }
      })
    },
    calculatePerSocialPay () {
      this.form.perSocialPay = (this.insuranceTable.tableData[0].perPensionRate +
        this.insuranceTable.tableData[0].perMedicalRate +
        this.insuranceTable.tableData[0].perUnemploymentRate) * this.form.socialBase
    },
    calculateComSocialPay () {
      this.form.comSocialPay = (this.insuranceTable.tableData[0].comPensionRate +
        this.insuranceTable.tableData[0].comMedicalRate +
        this.insuranceTable.tableData[0].comUnemploymentRate + this.insuranceTable.tableData[0].comMaternityRate +
        this.form.comInjuryRate) * this.form.socialBase
    },
    calculatePerHousePay () {
      this.form.perHousePay = this.form.perHouseRate * this.form.houseBase
    },
    calculateComHousePay () {
      this.form.comHousePay = this.form.comHouseRate * this.form.houseBase
    },
    /** 查询员工五险一金列表 */
    getList() {
      this.loading = true;
      listInsurance(this.queryParams).then(response => {
        this.insuranceList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        cityId: null,
        staffId: null,
        houseBase: null,
        perHouseRate: null,
        perHousePay: null,
        comHouseRate: null,
        comHousePay: null,
        socialBase: null,
        comSocialPay: null,
        perSocialPay: null,
        comInjuryRate: null,
        socialRemark: null,
        houseRemark: null,
        status: null,
        createTime: null,
        updateTime: null,
        isDeleted: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加员工五险一金";
    },
    allgetCity(){
      allgetCity().then(response => {
        this.CityList = response.data;
        
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      
    
      this.allgetCity()
      this.reset();
      this.form.staffId = row.staffId
      const id = row.id || this.ids
      this.open = true;
        this.title = "修改员工五险一金";
      if (row.cityId !== null) {
        getCity(row.cityId).then(response => {
          if (response.code === 200) {
            this.insuranceTable.tableData = [response.data]
          } else {
            this.$message.error(response.message)
          }
        })
        
        getInsurance(row.insuranceId).then(response => {
          if (response.code === 200) {
            this.form = response.data
            this.form.cityId =  ''+this.form.cityId
          } else {
            this.$message.error(response.message)
          }
        })
      }
    },
    /** 提交按钮 */
    submitForm() {
      console.log("sadffffffffffffffffff");
      console.log(this.form);
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id !==null) {
            updateInsurance(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          }else{
            
            addInsurance(this.form).then(response => {
              this.$modal.msgSuccess("添加成功");
              this.open = false;
              this.getList();
            });
          }
            
        
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除员工五险一金编号为"' + ids + '"的数据项？').then(function() {
        return delInsurance(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('hrmanagement/insurance/export', {
        ...this.queryParams
      }, `insurance_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
